-
Notifications
You must be signed in to change notification settings - Fork 31
jwttoken and user-agent validation #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Warning Rate limit exceeded@ravishanigarapu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 53 seconds before requesting another review. β How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. π¦ How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. π Files selected for processing (1)
WalkthroughThis update centralizes and standardizes the creation of HTTP request entities across multiple service classes by introducing a new utility, Changes
Sequence Diagram(s)sequenceDiagram
participant ServiceMethod
participant RestTemplateUtil
participant CookieUtil
participant UserAgentContext
participant RestTemplate
ServiceMethod->>RestTemplateUtil: createRequestEntity(body, authorization)
RestTemplateUtil->>CookieUtil: getJwtTokenFromCookie(request)
RestTemplateUtil->>UserAgentContext: getUserAgent()
RestTemplateUtil-->>ServiceMethod: HttpEntity with headers/body
ServiceMethod->>RestTemplate: exchange(url, HttpEntity, ...)
sequenceDiagram
participant HttpRequest
participant JwtUserIdValidationFilter
participant AuthorizationHeaderRequestWrapper
participant UserAgentContext
participant FilterChain
HttpRequest->>JwtUserIdValidationFilter: doFilter(request)
alt JWT in cookie or header
JwtUserIdValidationFilter->>AuthorizationHeaderRequestWrapper: wrap(request, "")
AuthorizationHeaderRequestWrapper->>FilterChain: doFilter(wrappedRequest)
else Mobile User-Agent with Authorization
JwtUserIdValidationFilter->>UserAgentContext: setUserAgent()
JwtUserIdValidationFilter->>FilterChain: doFilter(request)
JwtUserIdValidationFilter->>UserAgentContext: clear()
else
JwtUserIdValidationFilter-->>HttpRequest: 401 Unauthorized
end
Suggested reviewers
Poem
β¨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. πͺ§ TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
π§Ή Nitpick comments (3)
src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java (2)
11-11: Follow Java naming conventions for instance variables.The instance variable should use camelCase naming convention rather than PascalCase.
-private final String Authorization; +private final String authorization;Remember to update references to this variable in the rest of the class.
18-24: Consider extracting the header name as a constant.The string "Authorization" is used multiple times in the class. Extracting it as a constant would improve maintainability.
+private static final String AUTHORIZATION_HEADER = "Authorization"; @Override public String getHeader(String name) { - if ("Authorization".equalsIgnoreCase(name)) { - return Authorization; + if (AUTHORIZATION_HEADER.equalsIgnoreCase(name)) { + return authorization; } return super.getHeader(name); }src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
14-40: Add logging to track request entity creation.Adding logging would help with debugging and monitoring of the request entity creation process.
+import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class RestTemplateUtil { + private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class); + public static HttpEntity<Object> createRequestEntity(Object body, String authorization) { + logger.debug("Creating request entity with authorization: {}", authorization != null); ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); if (servletRequestAttributes == null) { + logger.debug("No servlet request attributes available, creating basic headers"); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8"); headers.add(HttpHeaders.AUTHORIZATION, authorization); return new HttpEntity<>(body, headers); } + logger.debug("Servlet request attributes available, creating complete headers"); HttpServletRequest requestHeader = servletRequestAttributes.getRequest(); // rest of the method... } }
π Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (15)
src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java(2 hunks)src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java(2 hunks)src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java(2 hunks)src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java(2 hunks)src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java(4 hunks)src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java(3 hunks)src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java(3 hunks)src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java(5 hunks)src/main/java/com/iemr/mmu/service/tele_consultation/TeleConsultationServiceImpl.java(2 hunks)src/main/java/com/iemr/mmu/utils/CookieUtil.java(1 hunks)src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java(2 hunks)src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java(1 hunks)src/main/java/com/iemr/mmu/utils/UserAgentContext.java(1 hunks)src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java(1 hunks)src/main/java/com/iemr/mmu/utils/http/HttpInterceptor.java(1 hunks)
π§° Additional context used
𧬠Code Graph Analysis (9)
src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
src/main/java/com/iemr/mmu/utils/UserAgentContext.java (1)
UserAgentContext(3-18)
src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java (1)
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
RestTemplateUtil(13-42)
β° Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyze (java)
π Additional comments (34)
src/main/java/com/iemr/mmu/utils/CookieUtil.java (1)
26-32: Good enhancement to JWT token extraction.Making
getJwtTokenFromCookiestatic with null-safety checking improves code robustness by preventing NullPointerExceptions when no cookies are present. This change properly supports the centralized JWT token handling across the application.src/main/java/com/iemr/mmu/utils/http/HttpInterceptor.java (1)
63-66: Good addition of early return for missing Authorization headers.This early check allows requests without an Authorization header to bypass further validation, which helps optimize request processing. The addition of the log message also aids in debugging and monitoring unauthorized requests.
src/main/java/com/iemr/mmu/service/tele_consultation/TeleConsultationServiceImpl.java (2)
62-62: Good addition of RestTemplateUtil import.Adding this import supports the refactoring to use the centralized HTTP request entity creation utility.
200-200: Improved HTTP entity creation with centralized utility.Replacing the manual construction of headers and cookie extraction with the centralized
RestTemplateUtil.createRequestEntitymethod improves code maintainability and consistency. This change aligns with the broader refactoring to standardize HTTP request handling across the application.src/main/java/com/iemr/mmu/service/common/master/RegistrarServiceMasterDataImpl.java (2)
65-65: Good addition of RestTemplateUtil import.Adding this import supports the refactoring to use the centralized HTTP request entity creation utility.
228-228: Improved HTTP entity creation with centralized utility.Replacing the manual construction of headers with the centralized
RestTemplateUtil.createRequestEntitymethod improves code maintainability and consistency. This change aligns with the broader refactoring to standardize HTTP request handling across the application.src/main/java/com/iemr/mmu/service/cancerScreening/CSCarestreamServiceImpl.java (2)
47-47: Added import for RestTemplateUtil.The added import supports the refactoring of HTTP entity creation.
67-67: Good refactoring: Centralized HTTP entity creation.Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method
RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.src/main/java/com/iemr/mmu/service/dataSyncActivity/UploadDataToServerImpl.java (2)
55-55: Added import for RestTemplateUtil.The added import supports the refactoring of HTTP entity creation.
376-376: Good refactoring: Centralized HTTP entity creation.Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method
RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.src/main/java/com/iemr/mmu/service/common/transaction/CommonServiceImpl.java (3)
82-82: Added import for RestTemplateUtil.The added import supports the refactoring of HTTP entity creation.
827-827: Good refactoring: Centralized HTTP entity creation in restTemplatePost method.Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method
RestTemplateUtil.createRequestEntity. This improves code maintainability and ensures consistent header handling across the application.
834-834: Good refactoring: Centralized HTTP entity creation in restTemplateGet method.Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method
RestTemplateUtil.createRequestEntity. This ensures consistent header handling for GET requests.src/main/java/com/iemr/mmu/service/common/transaction/CommonDoctorServiceImpl.java (2)
75-75: Added import for RestTemplateUtil.The added import supports the refactoring of HTTP entity creation.
910-910: Good refactoring: Centralized HTTP entity creation in callTmForSpecialistSlotBook method.Replaced manual HTTP header construction and JWT token extraction with a call to the centralized utility method
RestTemplateUtil.createRequestEntity. This ensures consistent header handling for specialist slot booking requests.src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerImpl.java (4)
56-56: Import added for the new utility class.The addition of RestTemplateUtil import supports the refactoring of HTTP request entity creation.
189-189: Good refactoring: Centralized HTTP entity creation.Replacing manual HTTP entity creation with RestTemplateUtil.createRequestEntity improves code maintainability and standardizes header management across the application.
336-336: Consistent usage of the RestTemplateUtil.The HTTP entity creation is properly refactored to use the central utility method, maintaining consistency with the rest of the codebase.
345-345: Consistent implementation for the second request.The second HTTP entity creation in the same method is also properly refactored to use RestTemplateUtil, ensuring consistent behavior across all API calls.
src/main/java/com/iemr/mmu/service/dataSyncActivity/DownloadDataFromServerTransactionalImpl.java (3)
55-55: Import added for the new utility class.The addition of RestTemplateUtil import supports the refactoring of HTTP request entity creation in this class.
247-247: Good refactoring: Centralized HTTP entity creation.Replacing manual HTTP entity creation with RestTemplateUtil.createRequestEntity improves code maintainability and standardizes header management across the application.
271-271: Consistent usage of the RestTemplateUtil for flag updates.The HTTP entity creation in updateProcessedFlagToCentral method is properly refactored to use the central utility method, maintaining consistency with the rest of the application.
src/main/java/com/iemr/mmu/utils/UserAgentContext.java (1)
1-18: Well-designed ThreadLocal implementation for User-Agent context.This is a good implementation of a thread-local context for storing User-Agent values, following Java best practices. The ThreadLocal approach ensures thread safety while making the User-Agent available throughout request processing without parameter passing.
The class properly provides methods to set, get, and clear the thread-local storage, which is essential for preventing memory leaks in thread-pooled environments.
src/main/java/com/iemr/mmu/utils/JwtUserIdValidationFilter.java (4)
9-10: Import added for the request wrapper.The addition of AuthorizationHeaderRequestWrapper import supports the new security enhancement to control Authorization header propagation.
77-80: Security enhancement: Controlled Authorization header propagation.Wrapping the request with AuthorizationHeaderRequestWrapper and passing an empty authorization header prevents downstream components from accessing the raw Authorization header after JWT validation, which is a good security practice.
82-90: Improved conditional structure for JWT validation.The restructured conditional logic with improved if-else if-else structure makes the code more readable and maintainable, clearly separating the different authentication scenarios.
91-101: Added support for mobile client authentication.This new code branch properly handles mobile clients by:
- Checking User-Agent header to identify mobile clients
- Setting the User-Agent in ThreadLocal context for downstream components
- Properly clearing the ThreadLocal in a finally block to prevent memory leaks
The try-finally block ensures proper resource cleanup even if an exception occurs during filter chain processing, which is a best practice.
src/main/java/com/iemr/mmu/service/registrar/RegistrarServiceImpl.java (5)
72-72: Good addition of the required import.The import of
RestTemplateUtilis necessary for the refactoring of HTTP request entity creation in multiple methods.
703-703: Centralizing HTTP request entity creation improves code maintainability.The refactoring removes duplicate code for manual header construction and standardizes the HTTP request entity creation process.
731-731: Consistent application of the refactoring pattern.The use of
RestTemplateUtil.createRequestEntityhere maintains consistency with other REST API calls.
751-751: Streamlined HTTP entity creation.The standardized approach for creating request entities simplifies the code and reduces potential for errors.
774-774: Consistent implementation of the utility method.This change completes the refactoring pattern across all REST API calls in the class.
src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java (1)
1-42: Well-implemented request wrapper for Authorization header handling.The class follows the standard wrapper pattern for HTTP servlet requests and correctly overrides the necessary methods to handle the Authorization header.
src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java (1)
13-42: Good centralization of HTTP request entity creation logic.The utility class effectively centralizes the creation of HTTP entities with appropriate headers, improving code maintainability and consistency across the application.
| public AuthorizationHeaderRequestWrapper(HttpServletRequest request, String authHeaderValue) { | ||
| super(request); | ||
| this.Authorization = authHeaderValue; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Add null check for authorization parameter.
The constructor should validate that the authorization parameter is not null to prevent NullPointerExceptions.
public AuthorizationHeaderRequestWrapper(HttpServletRequest request, String authHeaderValue) {
super(request);
+ if (authHeaderValue == null) {
+ throw new IllegalArgumentException("Authorization header value cannot be null");
+ }
this.Authorization = authHeaderValue;
}π€ Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/http/AuthorizationHeaderRequestWrapper.java
around lines 13 to 16, the constructor assigns the authorization parameter
without checking for null, which can cause NullPointerExceptions. Add a null
check for the authHeaderValue parameter at the start of the constructor and
throw an IllegalArgumentException or handle the null case appropriately to
ensure the parameter is not null before assignment.
| headers.add("JwtToken",requestHeader.getHeader("JwtToken")); | ||
| headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add null checks for header values.
The code doesn't handle cases where header values might be null, potentially leading to NullPointerException or unexpected behavior.
-headers.add("JwtToken",requestHeader.getHeader("JwtToken"));
-headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+// Add JwtToken header only if it exists in the request
+String jwtTokenHeader = requestHeader.getHeader("JwtToken");
+if (jwtTokenHeader != null) {
+ headers.add("JwtToken", jwtTokenHeader);
+}
+
+// Add cookie header only if JWT token was successfully extracted
+if (jwtTokenFromCookie != null) {
+ headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie);
+}π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| headers.add("JwtToken",requestHeader.getHeader("JwtToken")); | |
| headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie); | |
| // Add JwtToken header only if it exists in the request | |
| String jwtTokenHeader = requestHeader.getHeader("JwtToken"); | |
| if (jwtTokenHeader != null) { | |
| headers.add("JwtToken", jwtTokenHeader); | |
| } | |
| // Add cookie header only if JWT token was successfully extracted | |
| if (jwtTokenFromCookie != null) { | |
| headers.add(HttpHeaders.COOKIE, "Jwttoken=" + jwtTokenFromCookie); | |
| } |
π€ Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java around lines 36 to 37,
add null checks before adding header values to avoid NullPointerException.
Specifically, check if requestHeader.getHeader("JwtToken") and
jwtTokenFromCookie are not null before adding them to headers. If they are null,
either skip adding those headers or handle the null case appropriately to
prevent unexpected behavior.
| try { | ||
| jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader); | ||
|
|
||
| } catch (Exception e) { | ||
| e.printStackTrace(); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π οΈ Refactor suggestion
Improve exception handling for JWT token extraction.
The current implementation catches exceptions but only prints the stack trace without proper logging or fallback mechanism.
try {
jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader);
} catch (Exception e) {
- e.printStackTrace();
+ // Use logger instead of printStackTrace
+ logger.error("Error extracting JWT token from cookie", e);
+ // Consider setting a default value or taking appropriate action
}π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader); | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| } | |
| try { | |
| jwtTokenFromCookie = CookieUtil.getJwtTokenFromCookie(requestHeader); | |
| } catch (Exception e) { | |
| // Use logger instead of printStackTrace | |
| logger.error("Error extracting JWT token from cookie", e); | |
| // Consider setting a default value or taking appropriate action | |
| } |
π€ Prompt for AI Agents
In src/main/java/com/iemr/mmu/utils/RestTemplateUtil.java around lines 25 to 30,
the exception handling for extracting the JWT token from the cookie only prints
the stack trace, which is insufficient. Replace the printStackTrace call with
proper logging of the exception using a logger, and implement a fallback
mechanism such as returning a default value or rethrowing a custom exception to
handle the failure gracefully.
|



π Description
JIRA ID: AMM-1456
Please provide a summary of the change and the motivation behind it. Include relevant context and details.
β Type of Change
βΉοΈ Additional Information
Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Style